//
//  KKViewControllerAnimation.swift
//  KKViewController_Animation
//
//  Created by liaozhenming on 2016/12/15.
//  Copyright © 2016年 liaozhenming. All rights reserved.
//

import UIKit
import Foundation

class KKViewControllerAnimation: NSObject, UIViewControllerAnimatedTransitioning {

    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 3.0
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        
        //  目的viewController
        let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
        
        //  起始viewController
        let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
        
        //  添加toView到上下文
        transitionContext.containerView.insertSubview((toViewController?.view)!, belowSubview: (fromViewController?.view)!)
        
        //  自定义动画
        toViewController?.view.transform = CGAffineTransform.init(translationX: 320, y: 568)
        
        UIView.animate(withDuration: self.transitionDuration(using: transitionContext), animations: {()->Void in
            
            fromViewController?.view.transform = CGAffineTransform.init(translationX: -320, y: -568)
            toViewController?.view.transform = CGAffineTransform.identity
            
        }, completion: {(finished: Bool) -> Void in
            
            fromViewController?.view.transform = CGAffineTransform.identity
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        })
    }
}
